<template>
  <div class="search">
    <van-nav-bar fixed title="商品列表" left-arrow @click-left="$router.go(-1)" />

    <van-search
      readonly
      shape="round"
      background="#ffffff"
      :value="keyword"
      show-action
    >
      <template #action>
        <van-icon class="tool" name="apps-o" />
      </template>
    </van-search>

    <!-- 排序选项按钮 -->
    <div class="sort-btns">
      <div class="sort-item" :class="{active: index === 0}" @click="setSearchList(0)">综合</div>
      <div class="sort-item" :class="{active: index === 1}" @click="setSearchList(1)">销量</div>
      <div class="sort-item" :class="{active: index === 2}" @click="setSearchList(2)">价格 </div>
    </div>

    <div class="goods-list">
      <GoodsItem v-for="item in searchList" :key="item.goods_id" :item="item"></GoodsItem>
    </div>
  </div>
</template>

<script>
import GoodsItem from '@/components/GoodsItem.vue' // 商品组件
import { getSearchList } from '@/api/search' // 引入搜索列表请求

export default {
  name: 'SearchList',
  components: {
    GoodsItem
  },
  data () {
    return {
      searchList: [], // 搜索列表
      page: 1, // 当前页码
      index: 0 // 排序索引
    }
  },
  computed: {
    // 搜索关键词
    keyword () {
      return this.$route.query.keyword
    },
    // 搜索id
    searchId () {
      return this.$route.query.category_id
    }
  },
  created () {
    // 获取列表
    this.addSearchList({
      categoryId: this.searchId,
      sortType: 'all',
      goodsName: this.keyword,
      page: this.page
    })
  },
  methods: {
    // 封装获取列表函数
    async addSearchList (obj) {
      const result = await getSearchList(obj)
      this.searchList = result.data.list.data
    },
    // 设置排序
    // 0综合 1销量 2价格
    setSearchList (index) {
      this.index = index
      const sortType = ['all', 'sales', 'price']

      this.addSearchList({
        sortType: sortType[index],
        categoryId: this.searchId,
        goodsName: this.keyword,
        page: this.page
      })
    }
  }
}
</script>

<style lang="less" scoped>
.search {
  padding-top: 46px;
  ::v-deep .van-icon-arrow-left {
    color: #333;
  }
  .tool {
    font-size: 24px;
    height: 40px;
    line-height: 40px;
  }

  .sort-btns {
    display: flex;
    height: 36px;
    line-height: 36px;
    .sort-item {
      text-align: center;
      flex: 1;
      font-size: 16px;
    }
    .active {
      color: #ff5777;
    }
  }
}

// 商品样式
.goods-list {
  background-color: #f6f6f6;
}
</style>
